package com.example.serialization.serializable.transfer.socket;

// Server.java
import com.example.serialization.serializable.transfer.Message;

import java.io.*;
import java.net.ServerSocket;
import java.net.Socket;

public class Server {
    public static void main(String[] args) {
        final int PORT = 9090;

        try (ServerSocket serverSocket = new ServerSocket(PORT)) {
            System.out.println("服务端启动，等待客户端连接...");

            while (true) {
                // 接受客户端连接
                Socket clientSocket = serverSocket.accept();
                System.out.println("客户端已连接: " + clientSocket.getInetAddress());

                // 处理客户端请求
                new Thread(() -> handleClient(clientSocket)).start();
            }
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

    private static void handleClient(Socket clientSocket) {
        try (ObjectInputStream ois = new ObjectInputStream(clientSocket.getInputStream());
             ObjectOutputStream oos = new ObjectOutputStream(clientSocket.getOutputStream())) {

            // 读取客户端发送的消息
            Message request = (Message) ois.readObject();
            System.out.println("[服务端接收] " + request);

            // 构造响应消息
            Message response = new Message("服务端", request.getSender(), "已收到消息: " + request.getContent());

            // 发送响应
            oos.writeObject(response);
            oos.flush();
            System.out.println("[服务端发送] " + response);

        } catch (IOException | ClassNotFoundException e) {
            e.printStackTrace();
        } finally {
            try {
                clientSocket.close();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
    }
}